package com.imoresoft.agile.builder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.util.data.IData;
import com.imoresoft.agile.exception.ProException;
import com.imoresoft.agile.property.AppConstants;
import com.imoresoft.agile.property.PropsReaderForPic;
import com.imoresoft.agile.property.ProsReader;
import com.imoresoft.magic.util.Utils;
import com.taobao.api.domain.Item;

public class ModuleBuilder1 extends IModuleBuilder {

	public ModuleBuilder1(SuperDao superDao, IData userData, IData userStyle,
			String installPlace, String title) throws Exception {
		super(superDao, userData, userStyle, installPlace, title);
	}

	@SuppressWarnings("unchecked")
	public String buildPromHTML(List<Item> allItemListToBePromoted)
			throws ProException {

		String proModuleTemplate = this.getTempletCode()
				.getString("FRAME_CODE");

		// 替换search code
		String searchCode = buildSearchCode();
		proModuleTemplate = proModuleTemplate.replace("#{search_code}",
				searchCode);

		// 替换收藏店铺
		String favShopCode = StringUtils.EMPTY;
		if (AppConstants.FLAG_YES.equals(this.getUserStyle()
				.getString("IS_FAV"))) {
			favShopCode = this.getTempletCode().getString("FAV_SHOP_CODE");
		}
		proModuleTemplate = proModuleTemplate.replace("#{fav_shop_code}",
				favShopCode);

		// 替换旺旺
		String wangwangCode = StringUtils.EMPTY;
		if (AppConstants.FLAG_YES.equals(getUserStyle()
				.getString("IS_WANGWANG"))) {
			wangwangCode = getTempletCode().getString("WANGWANG_CODE");
		}
		proModuleTemplate = proModuleTemplate.replace("#{wangwang_code}",
				wangwangCode);

		// 替换pro_content
		String proContent = buildCode4AllItems(allItemListToBePromoted);
		proModuleTemplate = proModuleTemplate.replace("#{pro_content}",
				proContent);

		// 替换其它所有的@{}变量
		return replaceAllGloableVariables(proModuleTemplate);
	}

	private String buildSearchCode() {
		String keyWords = getUserStyle().getString("KEY_WORDS");
		if (StringUtils.isBlank(keyWords)) {
			return StringUtils.EMPTY;
		}
		String[] keyWordsArray = keyWords.split(",");
		String SingleSearchCode = this.getTempletCode()
				.getString("SEARCH_CODE");
		StringBuilder sb = new StringBuilder("");
		String seperator = "┊ ";
		int i = 0;
		for (String keyWord : keyWordsArray) {
			if (++i > 5) // 最多5个关键字
				break;
			String singleCode = StringUtils.replace(SingleSearchCode,
					"@{key_word}", keyWord);
			String encodeKeyWord = keyWord;
			try {
				encodeKeyWord = URLEncoder.encode(keyWord, "GBK");
			} catch (UnsupportedEncodingException e) {
			}
			singleCode = StringUtils.replace(singleCode, "@{encode_key_word}",
					encodeKeyWord);
			sb.append(singleCode);
			if (i < keyWordsArray.length)
				sb.append(seperator);
		}
		return sb.toString();
	}

	private String buildCode4AllItems(List<Item> allItemListToBePromoted) {
		StringBuilder prModuleHTML4AllItems = new StringBuilder("");
		String trCode = this.getTempletCode().getString("ITEM_TR_CODE");
		String tdCode = this.getTempletCode().getString("ITEM_TD_CODE");
		int numPerLine = getUserStyle().getInt("NUM_PER_LINE");
		for (int i = 0; i < allItemListToBePromoted.size(); i++) {
			Item itemToBePromoted = allItemListToBePromoted.get(i);
			if (i % numPerLine == 0) {
				prModuleHTML4AllItems.append(trCode); // 新一行推广位
			}
			prModuleHTML4AllItems.append(tdCode);
			String proModuleHTML4OneItem = buildProModule4OneItem(itemToBePromoted);
			prModuleHTML4AllItems.append(proModuleHTML4OneItem);
			prModuleHTML4AllItems.append("</td>");

			if ((i + 1) % numPerLine == 0
					|| i == allItemListToBePromoted.size() - 1) {
				prModuleHTML4AllItems.append("</tr>");// 一行推广位的结束
			}
		}
		return prModuleHTML4AllItems.toString();
	}

	private String buildProModule4OneItem(Item itemToBePromoted) {
		String proModuleHTML4OneItem = this.getTempletCode().getString(
				"ITEM_FRAME_CODE");
		String itemContentCode = buildItemContentCode(itemToBePromoted);
		proModuleHTML4OneItem = proModuleHTML4OneItem.replace(
				"#{item_content_code}", itemContentCode);
		return proModuleHTML4OneItem;
	}

	private String buildItemContentCode(Item itemToBePromoted) {
		StringBuilder itemContentCode = new StringBuilder();
		// append图片html
		String itemPicCode = this.getTempletCode().getString("ITEM_PIC_CODE");
		String isPromotionLable = getUserStyle()
				.getString("IS_PROMOTION_LABEL");
		// String promotionLableCode = StringUtils.EMPTY;
		String promotionLableCode = "<div style=\"width:@{td_height};height:@{td_width}; cursor:pointer;\"></div>";
		if (AppConstants.FLAG_YES.equals(isPromotionLable)) {
			promotionLableCode = this.getTempletCode().getString(
					"ITEM_PROM_LABEL_CODE");
		}
		itemPicCode = itemPicCode.replace("#{promotion_label_code}",
				promotionLableCode);
		itemContentCode.append(itemPicCode);

		// append title/price_label/buy_button的html
		String layout = getUserStyle().getString("LAYOUT");
		if (StringUtils.isNotBlank(layout)) {
			String[] elementArray = layout.split(",");
			for (String element : elementArray) {
				if ("item_price_code".equalsIgnoreCase(element)) {
					String priceStyle = getUserStyle().getString("PRICE_STYLE");
					String priceCode = this.getTempletCode().getString(
							"ITEM_PRICE_CODE_" + priceStyle);
					itemContentCode.append(priceCode);
				} else {
					String elmentCode = this.getTempletCode().getString(
							element.toUpperCase());
					itemContentCode.append(elmentCode);
				}
			}
		}

		// append已SaleoutNum Html
		String isSaleNum = getUserStyle().getString("IS_SALE_NUM");
		if (AppConstants.FLAG_YES.equals(isSaleNum)) {
			String saleText = getUserStyle().getString("SALE_TEXT");
			String saleOutCode = this.getTempletCode().getString(
					"ITEM_SALE_OUT_CODE");
			saleOutCode = saleOutCode.replace("@{sale_text}", saleText);
			itemContentCode.append(saleOutCode);
		}
		return replaceItemVariables(itemToBePromoted, itemContentCode
				.toString());
	}

	private String replaceItemVariables(Item itemToBePromoted,
			String itemContentCode) {
		// 宝贝IID
		itemContentCode = itemContentCode.replace("@{iid}", itemToBePromoted
				.getNumIid().toString());

		// 替换宝贝图片地址
		String picUrl = itemToBePromoted.getPicUrl();
		int numPerLine = getUserStyle().getInt("NUM_PER_LINE");
		String picSuffix = ProsReader.getString("TAOBAO_PIC_" + numPerLine);
		picUrl += picSuffix;
		itemContentCode = itemContentCode.replace("@{pic_url}", picUrl);

		// 替换宝贝名称
		String itemTitle = itemToBePromoted.getTitle();
		// if (itemTitle.length() > Constants.TITLE_LENGTH_TO_TRIM) {
		// itemTitle = itemTitle.substring(0, 18) + "··";
		// }
		itemContentCode = itemContentCode.replace("@{item_title}", itemTitle);

		// 替换价格
		String price = itemToBePromoted.getPrice();
		itemContentCode = itemContentCode.replace("@{price}", price);

		// 替换市场价
		String priceStyle = getUserStyle().getString("PRICE_STYLE");
		double PriceDouble = Double.parseDouble(price);
		int marketPriceMultiple = getUserStyle().getInt("MARKET_PRICE");// 市场价倍数
		String marketPrice = (PriceDouble * marketPriceMultiple / 100) + "";
		if ("2".equals(priceStyle)) {
			itemContentCode = itemContentCode.replace("@{market_price}",
					marketPrice);
		}

		return itemContentCode;
	}

	private String replaceAllGloableVariables(String proModuleTemplate) {
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{shop_url}", this.getUserSession().getString("SHOP_URL"));

		String title = this.getTitle();
		proModuleTemplate = StringUtils.replace(proModuleTemplate, "@{title}",
				title);

		proModuleTemplate = StringUtils.replace(proModuleTemplate, "@{color}",
				this.getTempletSkin().getString("COLOR"));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{sale_text}", this.getUserStyle().getString("SALE_TEXT"));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{buy_now_button}", PropsReaderForPic.getString(getUserStyle()
						.getString("BUY_BUTTON")));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{price_label}", PropsReaderForPic.getString(getUserStyle()
						.getString("PRICE_LABEL")));

		String promLabel = getUserStyle().getString("PROMOTION_LABEL");
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{promotion_label}", PropsReaderForPic.getString(promLabel));

		// 替换价格名称
		String marketPriceName = StringUtils.EMPTY;
		String realPriceName = StringUtils.EMPTY;
		String priceText = getUserStyle().getString("PRICE_TEXT");
		String priceStyle = getUserStyle().getString("PRICE_STYLE");
		if ("2".equals(priceStyle)) {
			if (StringUtils.isNotBlank(priceText)) {
				marketPriceName = priceText.split(",")[0].trim() + ":";
				realPriceName = priceText.split(",")[1].trim() + ":";
			}
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{market_price_name}", marketPriceName);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{real_price_name}", realPriceName);

		// 替换旺旺号码
		String wangwang = getUserStyle().getString("WANGWANG");
		try {
			if (StringUtils.isNotBlank(wangwang)) {
				wangwang = URLEncoder.encode(wangwang, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{encode_wangwang}", wangwang);

		// 原价是否要加划线
		String strikeStart = StringUtils.EMPTY;
		String strikeEnd = StringUtils.EMPTY;
		if (AppConstants.FLAG_YES.equals(getUserStyle().getString("IS_PRICE"))
				&& "2".equals(getUserStyle().getString("PRICE_STYLE"))
				&& AppConstants.FLAG_YES.equals(getUserStyle().getString(
						"IS_PRICE_STRIKE"))) {
			strikeStart = "<del>";
			strikeEnd = "</del>";
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{strike_start}", strikeStart);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{strike_end}", strikeEnd);

		// 替换table_id，预览的时候没有userPro信息
		String installPlace = this.getInstallPlace();
		if (StringUtils.isBlank(installPlace)) {
			installPlace = StringUtils.EMPTY;
		}
		proModuleTemplate = proModuleTemplate.replace("@{ipromotion_id}",
				"apro_" + installPlace);

		// 替换背景图片
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{top_bg_pic}", this.getTempletSkin().getString("TOP_BG_PIC"));
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{bottom_bg_pic}", this.getTempletSkin().getString(
						"BOTTOM_BG_PIC"));

		// 替换收藏店铺地址
		String addFavUrl = StringUtils.EMPTY;
		if (AppConstants.FLAG_YES.equals(getUserStyle().getString("IS_FAV"))) {
			addFavUrl = this.getUserSession().getString("ADD_FAV_URL");
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{add_fav_url}", addFavUrl);

		// 替换marquee
		String staticFlag = getUserStyle().getString("STATIC_FLAG");
		String marqueeStart = StringUtils.EMPTY;
		String marqueeEnd = StringUtils.EMPTY;
		String spacingLength = "11";
		String contentTableLength = "745";
		if (AppConstants.FLAG_NO.equals(staticFlag)) {
			marqueeStart = this.getTempletCode()
					.getString("MARQUEE_START_CODE");
			marqueeEnd = "</marquee>";
			spacingLength = "8";
			contentTableLength = "735";
		}
		proModuleTemplate = proModuleTemplate.replace("#{marquee_start}",
				marqueeStart);
		proModuleTemplate = proModuleTemplate.replace("#{marquee_end}",
				marqueeEnd);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{spacing_length}", spacingLength);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{content_table_length}", contentTableLength);

		// 替换item_td的高和宽度
		int numPerLine = this.getUserStyle().getInt("NUM_PER_LINE");
		String size = "170px";
		if (numPerLine == 5) {
			size = "130px";
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{td_height}", size);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{td_width}", size);

		String pro4Ipro = this.getUserStyle().getString("PRO4IPRO");
		String proText = Utils.getProModuleNoticeText(pro4Ipro);
		proModuleTemplate = proModuleTemplate.replace("@{pro4ipro}", proText);

		return proModuleTemplate;
	}

}
